package com.cms.entity;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.cms.util.DistributeUtils;
import com.cms.util.GroupUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.DateFormatUtils;

import com.alibaba.fastjson.annotation.JSONField;
import com.cms.entity.base.BaseOrder;
import com.cms.util.DBUtils;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;


/**
 * Entity -订单
 * 
 * 
 * 
 */
@SuppressWarnings("serial")
public class Order extends BaseOrder<Order> {
	
	/**
	 * 订单类型
	 */
	public enum Type{
		CART_BUY("购物车购买"),
		NOW_BUY("立刻购买"),
		GROUP_BUY("拼团购买"),
        SECKILL_BUY("秒杀购买");
		public String text;
		Type(String text){
			this.text = text;
		}
		public String getText(){
			return this.text;
		} 
	}
	
    /**
     * 订单状态
     */
	public enum Status{
		PENDING_PAYMENT("待付款"),
		PENDING_SHIPMENT("待发货"),
		SHIPPED("已发货"),
		COMPLETED("已完成"),
		CANCELED("已取消"),
		REFUND("已退款"),
		CLOSED("已关闭");
		public String text;
		Status(String text){
			this.text = text;
		}
		public String getText(){
			return this.text;
		} 
		public static Map<Integer, Order.Status> statusValueMap = new HashMap<>();
	    static {
            Order.Status[] values = Order.Status.values();
	        for (Order.Status status : values) {
	        	statusValueMap.put(status.ordinal(), status);
	        }
	    }
	}

    /**
     *
     * @return
     */
	public String getStatusKey(){
	    return Order.Status.statusValueMap.get(getStatus()).name();
    }

	
	public String getStatusName(){
		return Order.Status.statusValueMap.get(getStatus()).getText();
	}


    public String getPaymentMethodName(){
        return Payment.Method.methodValueMap.get(getPaymentMethod()).getText();
    }
    
    /**
     * 会员
     */
    private Member member;
    
    /**
     * 订单项
     */
    private List<OrderItem> orderItems;
    
    /**
     * 支付
     */
    private Payment payment;
    
    
    @JSONField(serialize=false)  
    private List<Pack> packs;
	
	public List<Pack> getPacks(){
		if(packs == null){
			packs = new Pack().dao().find("select * from cms_pack where orderId=?",getId());
        }
        return packs;
	}
    
    
    /**
     * 获取会员
     * 
     * @return  会员
     */
    public Member getMember(){
        if(member == null){
            member = new Member().dao().findById(getMemberId());
        }
        return member;
    }
    
    /**
     * 获取支付
     * 
     * @return  支付
     */
    public Payment getPayment(){
        if(payment == null){
        	payment = new Payment().dao().findFirst("select * from cms_payment where orderId=?",getId());
        }
        return payment;
    }

    /**
     * 获取订单总价格
     * 
     * @return 订单总价格
     */
    public BigDecimal getTotalPrice() {
        BigDecimal totalPrice = BigDecimal.ZERO;
        if (getOrderItems() != null) {
            for (OrderItem orderItem : getOrderItems()) {
                totalPrice = totalPrice.add(orderItem.getSubtotal());
            }
        }
        return totalPrice;
    }

    /**
     * 获取活动优惠
     *
     * @return
     */
    public BigDecimal getActivityPrice(){
        return getProductTotalPrice().subtract(getTotalPrice());
    }

    /**
     * 获取优惠总额
     *
     * @return
     */
    public BigDecimal getDiscountPrice(){
        BigDecimal couponAmount = getCouponAmount();
        if(couponAmount ==null){
            couponAmount = BigDecimal.ZERO;
        }
        return getActivityPrice().add(couponAmount);
    }

    /**
     * 获取商品总价格
     *
     * @return 商品总价格
     */
    public BigDecimal getProductTotalPrice() {
        BigDecimal productPrice = BigDecimal.ZERO;
        if (getOrderItems() != null) {
            for (OrderItem orderItem : getOrderItems()) {
                productPrice = productPrice.add(orderItem.getProductSubtotal());
            }
        }
        return productPrice;
    }

    /**
     * 获取总数量
     *
     * @return
     */
    public Integer getTotalQuantity() {
    	Integer totalQuantity = 0;
        if (getOrderItems() != null) {
            for (OrderItem orderItem : getOrderItems()) {
            	totalQuantity+=orderItem.getQuantity();
            }
        }
        return totalQuantity;
    }
    
    /**
     * 获取订单项
     * 
     * @return 订单项
     */
    public List<OrderItem> getOrderItems(){
        if(orderItems == null){
            orderItems = new OrderItem().dao().find("select * from cms_order_item where orderId=? ", getId());
        }
        return orderItems;
    }
    
    /**
     * 根据sn查找订单
     * 
     * @param sn
     *          
     * @return 订单
     */
    public Order findBySn(String sn){
        return findFirst("select * from cms_order where sn=? ",sn);
    }
    
    
    /**
     * 查找订单分页
     * 
     * @param pageNumber
     *            页码
     * @param pageSize
     *            每页记录数
     * @return 订单分页
     */
    public Page<Order> findPage(String sn,String consignee,Status status,Long memberId,String keyword,Integer pageNumber,Integer pageSize){
        String filterSql = " ";
        if(StringUtils.isNotBlank(sn)){
            filterSql+= " and sn like '%"+sn+"%'";
        }
        if(StringUtils.isNotBlank(consignee)){
            filterSql+= " and (consignee like '%"+consignee+"%' or phone like '%"+consignee+"%')";
        }
        if(status!=null){
        	filterSql+=" and status="+status.ordinal();
        }
        if(memberId!=null){
        	filterSql+=" and memberId="+memberId;
        }
        if(StringUtils.isNotBlank(keyword)){
        	filterSql+= " and (sn like '%"+keyword+"%' or name like '%"+keyword+"%') ";
        }
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        return paginate(pageNumber, pageSize, "select *", "from cms_order where 1=1 "+filterSql+orderBySql);
    }
    
    public Page<Order> findCouponPage(Long couponId,Integer pageNumber,Integer pageSize){
        String filterSql = " and id in(select orderId from cms_order_coupon where couponId="+couponId+") and status>0 ";
        String orderBySql = DBUtils.getOrderBySql("createDate desc");
        return paginate(pageNumber, pageSize, "select *", "from cms_order where 1=1 "+filterSql+orderBySql);
    }
    
    
    /**
     * 查找订单
     * 
     * @param status
     *          状态
     * @return 订单
     */
    public List<Order> findList(Integer status,Date beginDate,Date endDate){
    	String filterSql = " ";
        if(status!=null){
            filterSql+=" and status="+status;
        }
        if(beginDate!=null){
            filterSql+=" and completeDate>='"+DateFormatUtils.format(beginDate, "yyyy-MM-dd HH:mm:ss")+"'";
        }
        if(endDate!=null){
            filterSql+=" and completeDate<='"+DateFormatUtils.format(endDate, "yyyy-MM-dd HH:mm:ss")+"'";
        }
        return find("select * from cms_order where 1=1"+filterSql);
    }
    
    /**
     * 查找状态数量
     * @param status
     * @return
     */
    public Integer findCount(Long memberId,Integer status){
    	String filterSql = " ";
        if(memberId!=null){
            filterSql+=" and memberId="+memberId;
        }
        if(status!=null){
            filterSql+=" and status="+status;
        }
        return Db.queryInt("select count(1) from cms_order where 1=1"+filterSql);
    }

    /**
     * 支付完成
     */
    public void paymentComplete(String out_trade_no){
        String sn = out_trade_no.split("_")[0];
        Payment payment = new Payment().dao().findBySn(sn);
        payment.setModifyDate(new Date());
        payment.setStatus(Payment.Status.COMPLETED.ordinal());
        payment.update();
        if(Payment.Type.ORDER.ordinal()==payment.getType()){
            Order order = new Order().dao().findById(payment.getOrderId());
            order.setPaymentMethod(payment.getMethod());
            order.setModifyDate(new Date());
            order.setStatus(Order.Status.PENDING_SHIPMENT.ordinal());
            order.update();
            //拼团
            if(order.getType()== Type.GROUP_BUY.ordinal()){
                GroupUtils.updateCurrentNum(order);
            }
            //分销
            DistributeUtils.commission(order);
        }
    }

}
